// 704.二分查找
// import java.util.*;

class Solution {
    public int search(int[] nums, int target) {
        // 确保在区间内,只针对有值情况，[],3这种情况无法通过，应该去除下面的判断代码
        if (target < nums[0] || target > nums[nums.length -1]) {
            return -1;
        }
        int lef = 0, rig = nums.length -1;
        while (lef <= rig){
            // 位运算避免溢出
            int mid = lef + ((rig - lef) >> 1);
            if (nums[mid] == target){
                return mid;
            }else if(nums[mid] < target) {
                lef = mid + 1;
            }else {
                rig = mid - 1;
            }
        }
        return -1;
    }
}
// 开闭区间关键点：考虑边界值能否取上
// []区间，while(lef <= rig), lef = mid + 1, rig = mid - 1
// [)区间, 右边界无法取得，while(lef < rig), lef = mid + 1, rig = mid 
